package com.neusoft.EYSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.EYSystem.dao.ClientDAO;
import com.neusoft.EYSystem.dao.MealScheduleDAO;
import com.neusoft.EYSystem.dao.MealitemDAO;
import com.neusoft.EYSystem.dao.MealpickDAO;
import com.neusoft.EYSystem.po.*;
import com.neusoft.EYSystem.service.MealpickService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MealpickServiceImpl implements MealpickService {
    @Autowired
    private MealpickDAO mealpickDAO;
    @Autowired
    private MealScheduleDAO mealScheduleDAO;
    @Autowired
    private MealitemDAO mealitemDAO;
    @Autowired
    private ClientDAO clientDAO;

    private boolean isValid(String value) {
        return value != null && !value.trim().isEmpty() && !"null".equalsIgnoreCase(value.trim());
    }


    @Override
    public PageResponseBean<List<Mealitem>> getIncludedMeal(Long cur, Long number, Client client, MealSchedule mealSchedule) {
        List<Mealitem> fullList = new ArrayList<>();
        // 1. 根据 day + meal 找到 schedule_id
        QueryWrapper<MealSchedule> scheduleWrapper = new QueryWrapper<>();
        scheduleWrapper.eq("day", mealSchedule.getDay()).eq("meal", mealSchedule.getMeal());
        MealSchedule schedule = mealScheduleDAO.selectOne(scheduleWrapper);
        if (schedule == null) return new PageResponseBean<>(List.of());

        // 2. 根据 schedule_id + status=2 找出启用的 mealpick
        QueryWrapper<Mealpick> pickWrapper = new QueryWrapper<>();
        pickWrapper.eq("schedule_id", schedule.getScheduleId())
                .eq("status", "1")
                .eq("client_id", client.getClientId()); // 客户已选择的
        List<Mealpick> picks = mealpickDAO.selectList(pickWrapper);
        if (picks.isEmpty()) return new PageResponseBean<>(List.of());

        // 3. 获取菜品信息
        List<Integer> itemIds = picks.stream().map(Mealpick::getMealitemId).toList();
        List<Mealitem> mealitems = mealitemDAO.selectBatchIds(itemIds);

        // 4. 分页裁切
        int from = (int) ((cur - 1) * number);
        int to = Math.min(from + number.intValue(), mealitems.size());
        List<Mealitem> pageList = from < mealitems.size() ? mealitems.subList(from, to) : List.of();
        PageResponseBean<List<Mealitem>> rb = new PageResponseBean<>(pageList);
        rb.setTotal(pageList.size());
        return rb;
    }

    @Override
    public PageResponseBean<List<Mealitem>> getExcludedProjects(Long cur, Long number, Client client, MealSchedule mealSchedule) {
        // 1. 根据 day + meal 获取 schedule_id
        QueryWrapper<MealSchedule> scheduleWrapper = new QueryWrapper<>();
        scheduleWrapper.eq("day", mealSchedule.getDay()).eq("meal", mealSchedule.getMeal());
        MealSchedule schedule = mealScheduleDAO.selectOne(scheduleWrapper);

        if (schedule == null) return new PageResponseBean<>(List.of());

        Integer scheduleId = schedule.getScheduleId();

        // 2. 获取该 schedule_id 下 status=2 且未绑定客户（公共模板） 的膳食项
        QueryWrapper<Mealpick> publicPickWrapper = new QueryWrapper<>();
        publicPickWrapper.eq("schedule_id", scheduleId)
                .eq("status", "2")
                .isNull("client_id"); // 公共膳食模板
        List<Mealpick> publicPicks = mealpickDAO.selectList(publicPickWrapper);
        List<Integer> allItemIds = publicPicks.stream()
                .map(Mealpick::getMealitemId)
                .distinct()
                .toList();

        if (allItemIds.isEmpty()) return new PageResponseBean<>(List.of());

        // 3. 获取当前客户已选中的 itemId
        QueryWrapper<Mealpick> clientPickWrapper = new QueryWrapper<>();
        clientPickWrapper.eq("schedule_id", scheduleId)
                .eq("status", "1")
                .eq("client_id", client.getClientId());
        List<Mealpick> clientPicks = mealpickDAO.selectList(clientPickWrapper);
        List<Integer> clientItemIds = clientPicks.stream()
                .map(Mealpick::getMealitemId)
                .distinct()
                .toList();

        // 4. 取差集（未选中的 itemId）
        List<Integer> unchosenItemIds = allItemIds.stream()
                .filter(id -> !clientItemIds.contains(id))
                .toList();

        if (unchosenItemIds.isEmpty()) return new PageResponseBean<>(List.of());

        // 5. 查出未选中的菜品详情
        List<Mealitem> unchosenItems = mealitemDAO.selectBatchIds(unchosenItemIds);

        // 6. 分页裁切
        int from = (int) ((cur - 1) * number);
        int to = Math.min(from + number.intValue(), unchosenItems.size());
        List<Mealitem> pageList = from < unchosenItems.size() ? unchosenItems.subList(from, to) : List.of();

        // 7. 返回分页数据
        PageResponseBean<List<Mealitem>> rb = new PageResponseBean<>(pageList);
        rb.setTotal((long) unchosenItems.size());
        return rb;
    }

    @Override
    public ResponseBean<Integer> addMealpickService(Client client, MealSchedule mealSchedule, Mealitem mealitem) {
        ResponseBean<Integer> response = new ResponseBean<>();

        try {
            // 1. 根据 day + meal 查找 schedule_id
            QueryWrapper<MealSchedule> scheduleWrapper = new QueryWrapper<>();
            scheduleWrapper.eq("day", mealSchedule.getDay())
                    .eq("meal", mealSchedule.getMeal());
            MealSchedule schedule = mealScheduleDAO.selectOne(scheduleWrapper);

            if (schedule == null) {
                response.setStatus(400);
                response.setMsg("找不到对应的膳食时间安排");
                return response;
            }

            // 2. 构造 Mealpick 对象并插入
            Mealpick mealpick = new Mealpick();
            mealpick.setClientId(client.getClientId());
            mealpick.setMealitemId(mealitem.getMealitemId());
            mealpick.setScheduleId(schedule.getScheduleId());
            mealpick.setStatus("1"); // 订餐

            int result = mealpickDAO.insert(mealpick);
            if (result > 0) {
                response.setStatus(200);
                response.setMsg("添加膳食安排成功");
            } else {
                response.setStatus(500);
                response.setMsg("添加失败，数据库未插入任何数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            response.setMsg("添加膳食安排失败：" + e.getMessage());
        }

        return response;
    }

    @Override
    public ResponseBean<Integer> removeMealpickService(Client client, MealSchedule mealSchedule, Mealitem mealitem) {
        ResponseBean<Integer> response = new ResponseBean<>();

        try {
            // 1. 根据 day 和 meal 查找对应的膳食安排 schedule_id
            QueryWrapper<MealSchedule> scheduleWrapper = new QueryWrapper<>();
            scheduleWrapper.eq("day", mealSchedule.getDay())
                    .eq("meal", mealSchedule.getMeal());
            MealSchedule schedule = mealScheduleDAO.selectOne(scheduleWrapper);

            if (schedule == null) {
                response.setStatus(400);
                response.setMsg("找不到对应的膳食时间安排");
                return response;
            }

            // 2. 构造删除条件
            QueryWrapper<Mealpick> pickWrapper = new QueryWrapper<>();
            pickWrapper.eq("schedule_id", schedule.getScheduleId())
                    .eq("client_id", client.getClientId())
                    .eq("mealitem_id", mealitem.getMealitemId())
                    .eq("status", "1"); // 只删订餐的

            // 3. 执行删除
            int deleted = mealpickDAO.delete(pickWrapper);

            if (deleted > 0) {
                response.setStatus(200);
                response.setMsg("删除成功");
                response.setData(deleted);
            } else {
                response.setStatus(404);
                response.setMsg("未找到匹配的膳食安排记录");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            response.setMsg("删除失败：" + e.getMessage());
        }

        return response;
    }

    @Override
    public PageResponseBean<List<ClientAndScheduleAndItem>> pageClientAndScheduleAndItem(
            Long cur, Long number, Client client, MealSchedule mealSchedule, Mealitem mealitem) {

        List<ClientAndScheduleAndItem> fullList = new ArrayList<>();

        // 1. 查询 mealpick 表（只看 clientId + status=1）
        QueryWrapper<Mealpick> wrapperPick = new QueryWrapper<>();
        wrapperPick.eq("status", 1);
        if (client != null && client.getClientId() != null) {
            wrapperPick.eq("client_id", client.getClientId());
        }

        List<Mealpick> picks = mealpickDAO.selectList(wrapperPick);
        if (picks.isEmpty()) {
            PageResponseBean<List<ClientAndScheduleAndItem>> emptyResp = new PageResponseBean<>(List.of());
            emptyResp.setTotal(0L);
            emptyResp.setStatus(404);
            emptyResp.setMsg("未找到匹配的膳食安排记录");
            return emptyResp;
        }

        // 2. 提取所需 ID
        Set<Integer> clientIds = picks.stream()
                .map(Mealpick::getClientId)
                .collect(Collectors.toSet());
        Set<Integer> scheduleIds = picks.stream().map(Mealpick::getScheduleId).collect(Collectors.toSet());
        Set<Integer> mealitemIds = picks.stream().map(Mealpick::getMealitemId).collect(Collectors.toSet());

        // 3. 查 client 表
        List<Client> clientList = clientDAO.selectBatchIds(clientIds);
        Map<Integer, Client> clientMap = clientList.stream()
                .collect(Collectors.toMap(Client::getClientId, c -> c));

        // 4. 查 meal_schedule 表
        QueryWrapper<MealSchedule> scheduleWrapper = new QueryWrapper<>();
        scheduleWrapper.in("schedule_id", scheduleIds);
        if (mealSchedule != null) {
            if (isValid(mealSchedule.getDay())) {
                scheduleWrapper.eq("day", mealSchedule.getDay());
            }
            if (isValid(mealSchedule.getMeal())) {
                scheduleWrapper.eq("meal", mealSchedule.getMeal());
            }
        }
        List<MealSchedule> scheduleList = mealScheduleDAO.selectList(scheduleWrapper);
        Map<Integer, MealSchedule> scheduleMap = scheduleList.stream()
                .collect(Collectors.toMap(MealSchedule::getScheduleId, s -> s));

        // 5. 查 mealitem 表
        QueryWrapper<Mealitem> itemWrapper = new QueryWrapper<>();
        itemWrapper.in("mealitem_id", mealitemIds);
        if (mealitem != null && isValid(mealitem.getName())) {
            itemWrapper.like("name", mealitem.getName());
        }
        List<Mealitem> itemList = mealitemDAO.selectList(itemWrapper);
        Map<Integer, Mealitem> itemMap = itemList.stream()
                .collect(Collectors.toMap(Mealitem::getMealitemId, i -> i));

        // 6. 组装结果
        for (Mealpick pick : picks) {
            Client cli = clientMap.get(pick.getClientId());
            MealSchedule sched = scheduleMap.get(pick.getScheduleId());
            Mealitem item = itemMap.get(pick.getMealitemId());

            if (cli == null || sched == null || item == null) continue;

            ClientAndScheduleAndItem vo = new ClientAndScheduleAndItem();
            vo.setClient(cli);
            vo.setMealSchedule(sched);
            vo.setMealitem(item);
            fullList.add(vo);
        }

        // 7. 手动分页
        int fromIndex = (int) ((cur - 1) * number);
        int toIndex = Math.min(fromIndex + number.intValue(), fullList.size());
        List<ClientAndScheduleAndItem> pageList =
                fromIndex < fullList.size() ? fullList.subList(fromIndex, toIndex) : List.of();

        // 8. 返回分页响应（仿照你的 MealSchedule 方法）
        PageResponseBean<List<ClientAndScheduleAndItem>> rb = new PageResponseBean<>(pageList);
        rb.setTotal(fullList.size());
        return rb;
    }


}
